<template>
  <!--  take-photo-camera dialog  -->
  <el-dialog v-dialogDrag top="0vh" custom-class="rtc-private-video-dialog"
             :title="null" fullscreen :width="'100%'"
             :visible.sync="visible"
             :show-close="false"
             z-index="10000"
             :close-on-click-modal="false" :close-on-press-escape="false"
             @close="handleClose">
    <div class="camera-dialog-content">
      <div class="title">
        <div class="custom-btn-camera back flex-center" @click="handleClose"><img
            src="../../assets/image/all/back-camera.png" alt=""></div>
        <div class="text">Camera</div>
        <div class="custom-btn-camera flex-center camera-reverse" @click="flipCamera"><img
            src="../../assets/image/all/camera-reverse-circle.png" alt="Flip Camera"></div>
      </div>
      <!-- Media Container -->
      <div class="media-container">
        <video v-show="!showPhoto" ref="cam" width="100%" height="100%"
               muted autoPlay playsInline class="media-preview"></video>
        <canvas v-show="showPhoto" ref="photo" class="media-preview"></canvas>
      </div>
      <!-- Controls Section -->
      <div class="camera-controls">
        <!-- Mode Selection -->
        <div v-if="showModeSelection" class="mode-switch">
          <el-button-group class="mode-buttons">
            <el-button type="primary" @click="selectMode('photo')"
                       icon="el-icon-camera-solid" circle></el-button>
            <el-button type="primary" @click="selectMode('video')"
                       icon="el-icon-video-camera-solid" circle></el-button>
          </el-button-group>
        </div>

        <!-- Photo Controls -->
        <div v-if="!showModeSelection && mode === 'photo'"
             class="action-buttons">
          <el-button type="primary" @click="takePhoto"
                     icon="el-icon-camera" circle></el-button>
          <el-button type="success" @click="selectPhoto"
                     icon="el-icon-check" circle></el-button>
          <el-button type="danger" @click="cancelPhoto"
                     icon="el-icon-close" circle></el-button>
        </div>

        <!-- Video Controls -->
        <div v-if="!showModeSelection && mode === 'video'"
             class="action-buttons">
          <el-button :type="recording ? 'danger' : 'primary'"
                     :icon="recording ? 'el-icon-video-pause' : 'el-icon-video-play'"
                     @click="toggleRecording" circle></el-button>
          <el-button type="warning" @click="restartRecording"
                     :disabled="!recording && recordedBlobs.length === 0"
                     icon="el-icon-refresh-left" circle></el-button>
          <el-button type="success" @click="selectVideo"
                     :disabled="recordedBlobs.length === 0"
                     icon="el-icon-finished" circle></el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import ImCamera from "../../api/camera";
import {px2rem} from "@/utils/px2rem";

export default {
  name: 'CameraDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      mode: 'photo',
      showPhoto: false,
      showModeSelection: true,
      recordedBlobs: [],
      mediaRecorder: null,
      localStream: null,
      camera: new ImCamera(),
      recording: false,
      windowInnerHeight: 0,
      currentFrontCamera: true
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.initializeCamera();
      }
    }
  },
  methods: {
    // async openCamera() {
    //   try {
    //     const stream = await this.camera.openVideo(this.currentFrontCamera);
    //     this.localStream = stream;
    //     this.$nextTick(() => {
    //       this.$refs.cam.srcObject = stream;
    //       this.$refs.cam.muted = true;
    //     });
    //   } catch (e) {
    //     this.$message.error("Failed to open camera");
    //     console.error("This camera failed to open:", e.message);
    //   }
    // },
    async flipCamera() {
      try {
        const stream = await this.camera.switchCamera();
        this.localStream = stream;
        this.$refs.cam.srcObject = stream;
      } catch (e) {
        this.$message.error("Failed to switch camera");
      }
    },
    // flipCamera() {
    //   this.$data.currentFrontCamera = !this.$data.currentFrontCamera
    //   this.closeCamera()
    //   this.openCamera()
    // },
    // closeCamera() {
    //   if (this.localStream) {
    //     // 停止所有的摄像头流
    //     const tracks = this.localStream.getTracks();
    //     tracks.forEach(track => track.stop());
    //     this.localStream = null; // 清空本地流
    //   }
    // },
    async initializeCamera() {
      try {
        if (!this.localStream) {
          const stream = await this.camera.openVideo();
          this.localStream = stream;
          this.$refs.cam.srcObject = stream;
          this.$refs.cam.muted = true;
        }
      } catch (e) {
        this.$message.error("Camera failed to open");
        this.$emit('update:visible', false);
        console.error("Camera error:", e.message);
      }
    },
    px2rem,
    setFullHeight() {
      const height = window.innerHeight;
      this.$data.windowInnerHeight = window.innerHeight
      document.documentElement.style.setProperty('--vh', `${height}px`);
    },
    selectMode(newMode) {
      this.mode = newMode;
      this.showModeSelection = false;
      if (newMode === 'video') {
        this.$refs.cam.controls = false;
      } else {
        this.cancelPhoto();
      }
    },
    syncCanvasSize() {
      const video = this.$refs.cam;
      if (video) {
        const width = video.clientWidth;
        const height = video.clientHeight;
        return {width, height}
      }
    },
    takePhoto() {
      const {width, height} = this.syncCanvasSize();
      const canvas = this.$refs.photo;
      const ctx = canvas.getContext('2d');
      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(this.$refs.cam, 0, 0, width, height);
      this.showPhoto = true;
    },

    selectPhoto() {
      this.$refs.photo.toBlob(blob => {
        this.$emit('photo-selected', blob);
        this.handleClose();
      });
    },

    cancelPhoto() {
      this.showPhoto = false;
    },

    toggleRecording() {
      if (this.recording) {
        this.stopRecording();
      } else {
        this.startRecording();
      }
    },

    startRecording() {
      this.recordedBlobs = [];
      this.mediaRecorder = new MediaRecorder(this.localStream, {
        mimeType: 'video/webm;codecs=vp9'
      });

      this.mediaRecorder.ondataavailable = e => {
        if (e.data.size > 0) this.recordedBlobs.push(e.data);
      };

      this.mediaRecorder.start(100);
      this.recording = true;
    },

    stopRecording() {
      this.mediaRecorder.stop();
      this.recording = false;
    },

    restartRecording() {
      this.stopRecording();
      this.recordedBlobs = [];
      this.$refs.cam.srcObject = this.localStream;
    },

    selectVideo() {
      const blob = new Blob(this.recordedBlobs, {type: 'video/webm'});
      this.$emit('video-selected', blob);
      this.handleClose();
    },

    handleClose() {
      this.showModeSelection = true;
      this.mode = 'photo';
      this.showPhoto = false;
      this.recordedBlobs = [];
      this.recording = false;

      if (this.mediaRecorder) {
        this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
        this.mediaRecorder = null;
      }

      if (this.localStream) {
        this.localStream.getTracks().forEach(track => track.stop());
        this.localStream = null;
      }

      if (this.$refs.cam) {
        this.$refs.cam.srcObject = null;
        this.$refs.cam.load();
      }

      this.camera.close();

      this.$emit('update:visible', false);
      this.$emit('close');
    }
  },
  beforeDestroy() {
    if (this.localStream) {
      this.localStream.getTracks().forEach(track => track.stop());
    }
  },
  mounted() {
    window.addEventListener('resize', this.setFullHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.setFullHeight);
  },
}
</script>

<style lang="scss">
.rtc-private-video-dialog {
  background-image: url('../../assets/image/all/camera-bg.png') !important;
  background-size: 100% 100% !important;
}

.camera-dialog-content {
  padding: 20px;
  width: 100vw;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;

  .title {
    z-index: 999;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;

    .text {
      flex: 1;
      text-align: center;
      font-size: 22px;
      color: var(--im-color-white);
      //transform: translate(-24px, 0);
    }

    .back, .more {
      background: rgba(255, 255, 255, 0.1);
      box-shadow: 0 4px 12px rgba(13, 10, 44, 0.06);
    }

    .custom-btn-camera {
      background: rgba(255, 255, 255, 0.1);
      box-shadow: 0 4px 12px rgba(13, 10, 44, 0.06);
      width: 45px;
      height: 45px;
      border-radius: 50%;
    }

    .camera-reverse {
      width: 50px;
      height: 50px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .media-container {
    //background: #000;
    z-index: 0;
    position: absolute;
    top: 90px;
    left: 0;
    width: 100%;
    height: calc(100vh - 260px);
    padding: 0 20px;

    video {
      width: 100%;
      height: 100%;
    }
  }

  .camera-controls {
    //background: rgba(255,255,255,.9);
    z-index: 999;
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translate(-50%, 0);
    height: 100px;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  .media-container {
    .media-preview {
      border: 2px solid #e9ecef;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      background: #000;
    }
  }

  .camera-controls {
    width: 100%;
    padding: 20px 0 0;
    //border-top: 1px solid #dee2e6;

    .mode-buttons {
      display: flex;
      justify-content: center;

      .el-button {
        width: 48px;
        height: 48px;
        font-size: 20px;
        margin: 0 10px;
      }
    }

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 25px;

      .el-button {
        width: 56px;
        height: 56px;
        font-size: 24px;
        transition: all 0.3s ease;

        &:hover {
          transform: scale(1.1);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}
</style>